import { computed, inject, watch, type Ref } from "vue";
import { selectKey } from "./token";
import type { SelectOptionProxy } from "./types";

/**
 * 单个选项的逻辑
 */
export function useOption(props: {
  value: any;
  label?: string;
  disabled?: boolean;
}) {
  const select = inject(selectKey)!;

  // 当前标签
  const currentLabel = computed(() => {
    return props.label || String(props.value);
  });

  // 是否选中
  const itemSelected = computed(() => {
    const propsValue =
      typeof select.props === "object" && "value" in select.props
        ? (select.props as any).value
        : select.props;
    const multiple = propsValue?.multiple || false;
    const modelValue = propsValue?.modelValue;

    if (multiple) {
      const modelValueArray = Array.isArray(modelValue) ? modelValue : [];
      return modelValueArray.includes(props.value);
    } else {
      return modelValue === props.value;
    }
  });

  // 是否禁用
  const isDisabled = computed(() => {
    const propsRef =
      typeof select.props === "object" && "value" in select.props
        ? select.props
        : select.props;
    const disabled = "disabled" in propsRef ? propsRef.disabled : false;
    return props.disabled || disabled || false;
  });

  // 点击选项
  const selectOptionClick = () => {
    if (!isDisabled.value) {
      const option: SelectOptionProxy = {
        value: props.value,
        label: props.label || String(props.value),
        currentLabel: currentLabel.value,
        disabled: props.disabled || false,
        visible: true,
        hover: false,
        itemSelected: itemSelected.value,
        isDisabled: isDisabled.value,
        selectOptionClick,
      };
      select.handleOptionSelect(option);
    }
  };

  // 更新选项可见性（用于过滤）
  const updateOption = (query: string) => {
    const option = select.state.options.get(props.value);
    if (option) {
      const regexp = new RegExp(query, "i");
      option.visible = regexp.test(currentLabel.value);
    }
  };

  // 监听 value 变化
  watch(
    () => props.value,
    (newVal, oldVal) => {
      if (newVal !== oldVal) {
        select.onOptionDestroy(oldVal, {
          value: oldVal,
          label: props.label || String(oldVal),
          currentLabel: props.label || String(oldVal),
          disabled: props.disabled || false,
          visible: true,
          hover: false,
          itemSelected: false,
          isDisabled: false,
          selectOptionClick: () => {},
        });
        // 新选项会在组件挂载时通过 onOptionCreate 注册
      }
    }
  );

  return {
    currentLabel,
    itemSelected,
    isDisabled,
    selectOptionClick,
    updateOption,
  };
}

